package com.lvyq.myplayer.widget.self

import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.LinearInterpolator
import java.lang.Math.max
import java.lang.Math.min


class VinylView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 绘图工具
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    // 动画参数
    private val animator = ObjectAnimator.ofFloat(this, "rotation", 0f, 360f).apply {
        duration = 5000
        interpolator = LinearInterpolator()
        repeatCount = ObjectAnimator.INFINITE
    }

    // 转速控制（单位：RPM）
    var rpm = 33
        set(value) {
            field = value
            animator.duration = (60000 / value).toLong()
        }

    init {
        setOnClickListener { toggleRotation() }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // 绘制黑胶基底
        drawBaseDisc(canvas)

        //
        bitmapShader?.let { shader ->
            paint.shader = shader
            canvas.drawCircle(width / 2f, height / 2f, (min(width, height) / 2f).toFloat()-20f, paint)
        }

        // 绘制中心标签
        drawCenterLabel(canvas)


    }

    private fun drawBaseDisc(canvas: Canvas) {
        //paint.color = Color.parseColor("#212121")
        //绘制边缘
        var bottomPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        //30% 透明度 // 76 ≈ 30%
       // paint.color = Color.argb(76, 0x21, 0x21, 0x21)
        bottomPaint.color = Color.parseColor("#E6E6E6")
        canvas.drawCircle(width/2f, height/2f, width/2f, bottomPaint)

       /* paint.style = Paint.Style.FILL
        //80% 透明度
        paint.color = Color.argb(204, 0x21, 0x21, 0x21)
        canvas.drawCircle(width/2f, height/2f, width/2f-20, paint)
*/
        //图片覆盖


    }


    private fun drawCenterLabel(canvas: Canvas) {
        val centerRadius = width * 0.12f
        paint.style = Paint.Style.FILL
        paint.color = Color.WHITE
        canvas.drawCircle(width/2f, height/2f, centerRadius, paint)
        // 中心小孔
        paint.color = Color.parseColor("#616161")

        // 在 drawCenterLabel 方法中添加
        paint.color = Color.RED
        paint.textSize = centerRadius * 0.5f
        paint.textAlign = Paint.Align.CENTER
        canvas.drawText("Audio", width/2f, height/2f + paint.textSize/3, paint)
        canvas.drawCircle(width/2f, height/2f, centerRadius * 0.3f, paint)
    }



    fun toggleRotation() {
        if (animator.isRunning) {
            animator.pause()
        } else {
            animator.resume()
        }
    }

    fun startRotation() = animator.start()
    fun stopRotation() = animator.cancel()

    /**
     * 监听拖动事件
     */
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        //获取控件位置
        println("宽度>>"+width+"高度>>"+height)


        return true

    }
    private var bitmap: Bitmap? = null
    private var bitmapShader: BitmapShader? = null
    // 设置图片（支持资源ID和Bitmap）
    fun setImageResource(resId: Int) {
        bitmap = BitmapFactory.decodeResource(resources, resId)
        updateShader()
    }

    fun setImageBitmap(bitmap: Bitmap) {
        this.bitmap = bitmap
        updateShader()
    }

    private fun updateShader() {
        bitmap?.let {
            bitmapShader = BitmapShader(
                it,
                Shader.TileMode.CLAMP,
                Shader.TileMode.CLAMP
            )
            // 设置默认缩放类型为centerCrop
            bitmapShader?.setLocalMatrix(calculateCropMatrix(it))
        }
        invalidate()
    }

    // 计算centerCrop的矩阵
    private fun calculateCropMatrix(bitmap: Bitmap): Matrix {
        val matrix = Matrix()
        val scale = max(width.toFloat() / bitmap.width, height.toFloat() / bitmap.height)
        matrix.setScale(scale, scale)
        matrix.postTranslate(
            (width - bitmap.width * scale) / 2f,
            (height - bitmap.height * scale) / 2f
        )
        return matrix
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        bitmapShader?.let { shader ->
            shader.setLocalMatrix(calculateCropMatrix(bitmap!!))
        }
    }


    // 释放资源
    fun recycleBitmap() {
        bitmap?.recycle()
        bitmap = null
        bitmapShader = null
    }
}
